package com.wlt.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 *   登录拦截器
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor{
	/**
	 * 进入Handler方法之前执行
	 * 用于身份认证,身份授权
	 * 
	 */
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//获取请求的url
		String url=request.getRequestURI();
		//判断url是否是公开地址(实际使用时将公开地址配置在配置文件中)
		//这里公开地址是登录提交的地址
		if(url.indexOf("login.do")>=0) {
			//如果进行登录提交,放行
			return true;
		}
		//判断session
		HttpSession session=request.getSession();
		//从session中取出用户身份信息
		String username = (String) session.getAttribute("username");
		if(username != null) {
			//身份存在 放行
			return true;
		}
		//执行到这里表示用户需要身份认证,跳转到登录页
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}
	//进入Handler方法之后,返回modelAndView之前执行
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}
	//执行Handler完成执行此方法
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}
	

}
